#include "listorganizer.h"
#include "ui_listorganizer.h"

#include<Qt>
#include<QMessageBox>
#include<QFileDialog>
#include<QStatusBar>
#include<string.h>

ListOrganizer::ListOrganizer(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::ListOrganizer)
{
    ui->setupUi(this);
    ui->lineEdit->setFocus();
    saved = false;
    savedRecently = false;
    //ui->listWidget->setUpdatesEnabled(true);

    //Connect GUI buttons to appropriate slots
    connect(ui->submitButton,SIGNAL(clicked()),this,SLOT(Submit()));
    connect(ui->lineEdit,SIGNAL(returnPressed()),this,SLOT(Submit()));
    connect(ui->sortAscButton,SIGNAL(clicked()),this,SLOT(SortListAscending()));
    connect(ui->sortDescButton,SIGNAL(clicked()),this,SLOT(SortListDescending()));
    connect(ui->deleteAllButton,SIGNAL(clicked()),this,SLOT(DeleteAllListItems()));
    connect(ui->editItemButton,SIGNAL(clicked()),this,SLOT(EditItem()));
    connect(ui->deleteButton,SIGNAL(clicked()),this,SLOT(DeleteSingleItem()));
    connect(ui->moveDownButton,SIGNAL(clicked()),this,SLOT(MoveItemDown()));
    connect(ui->moveUpButton,SIGNAL(clicked()),this,SLOT(MoveItemUp()));
    connect(ui->listWidget,SIGNAL(clicked(QModelIndex)),this,SLOT(ShowItemOptions()));
    connect(ui->listWidget, SIGNAL(doubleClicked(QModelIndex)),this,SLOT(EditItem()));
    connect(ui->listWidget,SIGNAL(currentTextChanged(QString)),this,SLOT(ModifiedSinceSave()));


    // Connect actions to appropriate slots
    connect(ui->actionAscending,SIGNAL(triggered()),this,SLOT(SortListAscending()));
    connect(ui->actionDescending,SIGNAL(triggered()),this,SLOT(SortListDescending()));
    connect(ui->actionE_xit,SIGNAL(triggered()),this,SLOT(close()));
    connect(ui->actionAbout_This_Product,SIGNAL(triggered()),this,SLOT(AboutProduct()));
    connect(ui->actionDelete_Current_List,SIGNAL(triggered()),this,SLOT(DeleteAllListItems()));
    //connect(ui->action_Save_List,SIGNAL(triggered()),this,SLOT(SaveList()));
    connect(ui->action_Save_List,SIGNAL(triggered()),this,SLOT(SaveList2()));
    //connect(ui->action_Open_List,SIGNAL(triggered()),this,SLOT(OpenList()));
    connect(ui->action_Open_List,SIGNAL(triggered()),this,SLOT(OpenList2()));
    connect(ui->actionSave_As,SIGNAL(triggered()),this,SLOT(SaveAs()));
    connect(ui->actionAbout_This_Product,SIGNAL(hovered()),this,SLOT(AboutProductStatus()));
    connect(ui->actionAdd_List_Item,SIGNAL(triggered()),ui->lineEdit,SLOT(setFocus()));
    connect(ui->action_Tutorial,SIGNAL(hovered()),this,SLOT(TutorialStatus()));
    connect(ui->action_Tutorial,SIGNAL(triggered()),this,SLOT(Tutorial()));
    connect(ui->action_New_List,SIGNAL(triggered()),this,SLOT(NewList()));
    connect(ui->actionRedo,SIGNAL(triggered()), this, SLOT(Redo()));
    connect(ui->actionUndo,SIGNAL(triggered()), this, SLOT(Undo()));
    //connect(ui->mainToolBar->)

    // Set up GUI so that empty list disables buttons
    ui->moveDownButton->setEnabled(false);
    ui->moveUpButton->setEnabled(false);
    ui->deleteButton->setEnabled(false);
    ui->deleteAllButton->setEnabled(false);
    ui->sortAscButton->setEnabled(false);
    ui->sortDescButton->setEnabled(false);
    ui->editItemButton->setEnabled(false);
    ui->actionAscending->setEnabled(false);
    ui->actionDescending->setEnabled(false);
    ui->actionRedo->setEnabled(false);
    ui->actionUndo->setEnabled(false);

    lastAction = 0;
    /*if (ui->lineEdit->text() != "")
    {
        QString text = ui->lineEdit->text();
        ui->listWidget->setText(text);
    }
    Submit();
*/
}

ListOrganizer::~ListOrganizer()
{
    delete ui;
}

void ListOrganizer::changeEvent(QEvent *e)
{
    QMainWindow::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

void ListOrganizer::Submit()
{
    QString newtext = ui->lineEdit->text();
    int total = ui->listWidget->count();
    for (int i = 0; i < total; i++)
    {
        if (ui->listWidget->item(i)->text() == newtext)
        {
            QMessageBox::information(this,tr("Record Already Exists"), tr("The list you have created already contains a record with this label."));
            ui->lineEdit->clear();
            ui->lineEdit->setFocus();
            return;
        }
    }

    if (newtext != "")
    {
        ui->listWidget->addItem(newtext);
        savedRecently = false;
        lastAction = 1;
        ui->actionUndo->setEnabled(true);
    }
    if (ui->listWidget->count() > 0)
    {
        ui->deleteAllButton->setEnabled(true);
        ui->sortAscButton->setEnabled(true);
        ui->sortDescButton->setEnabled(true);
        ui->actionAscending->setEnabled(true);
        ui->actionDescending->setEnabled(true);
    }
    ui->lineEdit->clear();
    ui->lineEdit->setFocus();
}

void ListOrganizer::SortListAscending()
{
    ui->listWidget->sortItems(Qt::AscendingOrder);
    savedRecently = false;
}

void ListOrganizer::SortListDescending()
{
    ui->listWidget->sortItems(Qt::DescendingOrder);
    savedRecently = false;
}

void ListOrganizer::DeleteAllListItems()
{
    QMessageBox::StandardButton reply;
    reply = QMessageBox::question(this,tr("Deletion Notice"), tr("Are you sure you want to delete the list?"), QMessageBox::Yes | QMessageBox::No);
    if (reply == QMessageBox::Yes)
    {
        // Delete all items from list
        ui->listWidget->clear();
        // Move focus to line edit
        ui->lineEdit->setFocus();

        // Make all buttons disabled because list is empty
        ui->editItemButton->setEnabled(false);
        ui->deleteButton->setEnabled(false);
        ui->moveUpButton->setEnabled(false);
        ui->moveDownButton->setEnabled(false);
        ui->sortAscButton->setEnabled(false);
        ui->sortDescButton->setEnabled(false);
        ui->deleteAllButton->setEnabled(false);
        ui->actionDelete_Current_List->setEnabled(false);
        ui->actionAscending->setEnabled(false);
        ui->actionDescending->setEnabled(false);

        saved = false;
    }
}

void ListOrganizer::DeleteSingleItem()
{
    int row = ui->listWidget->currentRow();
    ui->listWidget->takeItem(row);
    if (ui->listWidget->count() == 0)
    {
        ui->editItemButton->setEnabled(false);
        ui->deleteButton->setEnabled(false);
        ui->moveDownButton->setEnabled(false);
        ui->moveUpButton->setEnabled(false);
        ui->actionDelete_Current_List->setEnabled(false);
        ui->actionAscending->setEnabled(false);
        ui->actionDescending->setEnabled(false);
    }
    savedRecently = false;
}

void ListOrganizer::EditItem()
{
    QListWidgetItem *item;
    item = ui->listWidget->currentItem();
    //QFlag *flag;
    //item->setFlags(Qt::ItemIsUserCheckable);
    item->setFlags(Qt::ItemFlags(63));
    //int num = item->flags();
    //ui->lcdNumber->display(num);
    ui->listWidget->editItem(item);
    //ui->listWidget->setItemHidden(item,true);
    Verify();
    item->setFlags(Qt::ItemFlags(53));
}

void ListOrganizer::MoveItemDown()
{
    // Determine how many records are in the list
    int totalRows = ui->listWidget->count();
    // Determine the row of the currently selected item
    int row = ui->listWidget->currentRow();
    // "Move" selected item by inserting it two rows down and deleting the previous entry
    if (row != totalRows - 1)
    {
        QListWidgetItem *item;
        item = ui->listWidget->currentItem();
        QString text = item->text();
        ui->listWidget->insertItem(row+2,text);
        ui->listWidget->takeItem(row);
        ui->listWidget->setCurrentRow(row+1);
    }
    savedRecently = false;
}

void ListOrganizer::MoveItemUp()
{
    // Determine the row of the currently selected item
    int row = ui->listWidget->currentRow();
    // "Move" selected item by inserting it one row above and deleting the previous entry
    if (row != 0)
    {
        QListWidgetItem *item;
        item = ui->listWidget->currentItem();
        QString text = item->text();
        ui->listWidget->insertItem(row-1,text);
        ui->listWidget->takeItem(row+1);
        ui->listWidget->setCurrentRow(row-1);
    }
    savedRecently = false;
}

void ListOrganizer::ShowItemOptions()
{
    ui->editItemButton->setEnabled(true);
    ui->deleteButton->setEnabled(true);
    ui->moveDownButton->setEnabled(true);
    ui->moveUpButton->setEnabled(true);
}

void ListOrganizer::Exit()
{
    //int count = ui->listWidget->count();

    /*
    for (int i = 0; i < count; i++)
    {
        if (ui->listWidget->currentRowChanged(i))
        {
           // Prompt for save
           exit(0);
        }
    }
    */
    exit(0);
}

void ListOrganizer::AboutProduct()
{
    QMessageBox::information(this,tr("About This Product"),
       tr("This program was created by the amazing QT developer, Tyler Steinle, for CSC 403.\n\n\
Donations are currently being accepted and may be sent to the esteemed developer at 555 Broke Avenue, Madison SD 57042.  \
Your contributions are vital to the continued development of this fantastic program.\n\n\
Look for new changes coming soon!"));
    return;
}

void ListOrganizer::Tutorial()
{

QMessageBox::information(this,tr("Tutorial"),
       tr("Creating a List\nTo create a list, simply begin typing in the text box, and press Enter to add the item to the list.\n\
Saving a List\n\nTo save a list, simply click on the Save List icon in the taskbar, or select File, then Save List.  This will bring up \
the Save List directory from which you can select the location and filename where you would like to save your list.\n\n\
<b>Loading a Saved List<\\b>\n\nTo access a previously saved list, simply click on the Open List icon in the taskbar, or select File, then \
Open List.  This will bring up the Load List directory from which you can select the list you would like to load.\
Your contributions are vital to the continued development of this fantastic program.\n\n\
Look for new changes coming soon!"));
    return;
    /*
    //if (!tutorialDialog)
    tutorialDialog = new QDialog(this);
    tutorialDialog->show();
    tutorialDialog->setModal(true);
    tutorialDialog->raise();
    tutorialDialog->activateWindow();
    tutorialDialog->setSizeGripEnabled(true);
    */
}

void ListOrganizer::OpenList()
{
    QString fileName = QFileDialog::getOpenFileName(this,tr("Open List"), "",tr("List (*.lst);;All Files (*)"));
    if (fileName.isEmpty())
         return;
    else
    {
         QFile file(fileName);
         if (!file.open(QIODevice::ReadOnly))
         {
             QMessageBox::information(this, tr("Unable to open file"),
                 file.errorString());
             return;
         }

         QDataStream in(&file);
         in.setVersion(QDataStream::Qt_4_6);
         //in >> ui->listWidget;
     }
}

void ListOrganizer::OpenList2()
{
    if (savedRecently == false && ui->listWidget->count() != 0)
    {
        QMessageBox::StandardButton reply;
        reply = QMessageBox::question(this,tr("Deletion Notice"), tr("You are about to open a saved list.\
  Would you like to save your current list before opening an existing one?"), QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel);

        if (reply == QMessageBox::Yes)
        {
            if(!SaveList2())
                return;
        }
        else if (reply == QMessageBox::Cancel)
            return;
        else if (reply == QMessageBox::No)
        {
            // Delete all items from list
            ui->listWidget->clear();
            // Move focus to line edit
            ui->lineEdit->setFocus();

            // Make all buttons disabled because list is empty
            ui->editItemButton->setEnabled(false);
            ui->deleteButton->setEnabled(false);
            ui->moveUpButton->setEnabled(false);
            ui->moveDownButton->setEnabled(false);
            ui->sortAscButton->setEnabled(false);
            ui->sortDescButton->setEnabled(false);
            ui->deleteAllButton->setEnabled(false);
            ui->actionDelete_Current_List->setEnabled(false);
            ui->actionAscending->setEnabled(false);
            ui->actionDescending->setEnabled(false);

            ui->tableLabel->setText("Untitled List");
            saved = false;
        }
    }

    ui->listWidget->clear();
    FILE * infile;
    QString fileName = QFileDialog::getOpenFileName(this,tr("Open List"), "",tr("List (*.lst);;All Files (*)"));
    QString endFileName = fileName.section('/', -1);
    char * charFileName;
    QByteArray ba = fileName.toLocal8Bit();
    charFileName = ba.data();

    int i = 0;
    char text[20];

    infile = fopen(charFileName,"r");
    if (infile == NULL)
        return;
    //    QMessageBox::information(this, tr("Unable to open file"), tr("This file does not exist."));

    else while(fgets(text, 19, infile) != NULL)
        {
            text[strlen(text)-1] = '\0';
            //fscanf(infile,"%s",text);
            //QString(text).fromAscii(text,29);
            QString(text).fromStdString(text);
            ui->listWidget->addItem(text);
            i++;
        }
    fclose(infile);

    ui->tableLabel->setText(endFileName);
}


void ListOrganizer::SaveList()
{
    QString fileName = QFileDialog::getSaveFileName(this,tr("Save List"),"",tr("List (*.lst);;All Files(*)"));

    if (fileName.isEmpty())
        return;
    else
    {
        QFile file(fileName);
        if (!file.open(QIODevice::WriteOnly))
        {
            QMessageBox::information(this,tr("Unable to open file"), file.errorString());
            return;
        }

        QDataStream out(&file);
        out.setVersion(QDataStream::Qt_4_6);
        out << ui->listWidget;
    }
}

bool ListOrganizer::SaveList2()
{
    if (saved == false)
    {
        return SaveAs();
    }

    else
    {
        FILE * outfile;
        char * FileName;
        FileName = charFileName;
        outfile = fopen(FileName,"w");
        int count = ui->listWidget->count();
        for (int i = 0; i < count; i++)
        {
             QString mytext = ui->listWidget->item(i)->text();
             fprintf(outfile,"%s\n",(mytext.toAscii().data()));
        }
        fclose(outfile);
        saved = true;
        savedRecently = true;
        return true;
    }
}

bool ListOrganizer::SaveAs()
{
    FILE * outfile;
    QString fileName = QFileDialog::getSaveFileName(this,tr("Save List"),"",tr("List (*.lst);;All Files(*)"));
    if (fileName.isEmpty())
        return false;
    else
    {
        QString endFileName = fileName.section('/', -1);
        QByteArray ba = fileName.toLocal8Bit();
        charFileName = ba.data();
        outfile = fopen(charFileName,"w");
        int count = ui->listWidget->count();
        for (int i = 0; i < count; i++)
        {
             QString mytext = ui->listWidget->item(i)->text();
             fprintf(outfile,"%s\n",(mytext.toAscii().data()));
        }
        fclose(outfile);
        saved = true;
        savedRecently = true;
        ui->tableLabel->setText(endFileName);
        return true;
    }
}

void ListOrganizer::NewList()
{
    if (savedRecently == false && ui->listWidget->count() != 0)
    {
        QMessageBox::StandardButton reply;
        reply = QMessageBox::question(this,tr("Deletion Notice"), tr("You are about to create a new list.\
 Would you like to save your current list before creating a new one?"), QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel);
        if (reply == QMessageBox::Yes)
        {
            SaveAs();

            // Delete all items from list
            ui->listWidget->clear();
            // Move focus to line edit
            ui->lineEdit->setFocus();

            // Make all buttons disabled because list is empty
            ui->editItemButton->setEnabled(false);
            ui->deleteButton->setEnabled(false);
            ui->moveUpButton->setEnabled(false);
            ui->moveDownButton->setEnabled(false);
            ui->sortAscButton->setEnabled(false);
            ui->sortDescButton->setEnabled(false);
            ui->deleteAllButton->setEnabled(false);
            ui->actionDelete_Current_List->setEnabled(false);
            ui->actionAscending->setEnabled(false);
            ui->actionDescending->setEnabled(false);

            ui->tableLabel->setText("Untitled List");
            saved = false;
        }
        else if (reply == QMessageBox::Cancel)
            ;
        else if (reply == QMessageBox::No)
        {
            // Delete all items from list
            ui->listWidget->clear();
            // Move focus to line edit
            ui->lineEdit->setFocus();

            // Make all buttons disabled because list is empty
            ui->editItemButton->setEnabled(false);
            ui->deleteButton->setEnabled(false);
            ui->moveUpButton->setEnabled(false);
            ui->moveDownButton->setEnabled(false);
            ui->sortAscButton->setEnabled(false);
            ui->sortDescButton->setEnabled(false);
            ui->deleteAllButton->setEnabled(false);
            ui->actionDelete_Current_List->setEnabled(false);
            ui->actionAscending->setEnabled(false);
            ui->actionDescending->setEnabled(false);

            ui->tableLabel->setText("Untitled List");
            saved = false;
        }
    }
    else
    {
        // Delete all items from list
        ui->listWidget->clear();
        // Move focus to line edit
        ui->lineEdit->setFocus();

        // Make all buttons disabled because list is empty
        ui->editItemButton->setEnabled(false);
        ui->deleteButton->setEnabled(false);
        ui->moveUpButton->setEnabled(false);
        ui->moveDownButton->setEnabled(false);
        ui->sortAscButton->setEnabled(false);
        ui->sortDescButton->setEnabled(false);
        ui->deleteAllButton->setEnabled(false);
        ui->actionDelete_Current_List->setEnabled(false);
        ui->actionAscending->setEnabled(false);
        ui->actionDescending->setEnabled(false);

        ui->tableLabel->setText("Untitled List");
        saved = false;
    }
}

void ListOrganizer::ModifiedSinceSave()
{
    savedRecently = false;
}


void ListOrganizer::Verify()
{
    QString inputtext = ui->listWidget->currentItem()->text();
    int total = ui->listWidget->count();
    int currow = ui->listWidget->currentRow();

    if (inputtext == "")
        ui->listWidget->takeItem(currow);
    for (int i = 0; i < currow; i++)
    {
        if (ui->listWidget->item(i)->text() == inputtext)
        {
            QMessageBox::information(this,tr("Record Already Exists"), tr("The list you have created already contains a record with this label."));
            ui->listWidget->takeItem(currow);
            return;
        }
    }

    for (int i = currow + 1; i < total; i++)
    {
        if (ui->listWidget->item(i)->text() == inputtext)
        {
            QMessageBox::information(this,tr("Record Already Exists"), tr("The list you have created already contains a record with this label."));
            ui->listWidget->takeItem(currow);
            return;
        }
    }
}

void ListOrganizer::AboutProductStatus()
{
    ui->statusBar->showMessage(tr("Display information about List Organizer"));
}

void ListOrganizer::TutorialStatus()
{
    ui->statusBar->showMessage(tr("Display tutorial for List Organizer"));
}

void ListOrganizer::Undo()
{
    if (lastAction == 1)
    {
        int count = ui->listWidget->count();
        ui->listWidget->takeItem(count - 1);
    }
    else if (lastAction == 2)
;

}



void ListOrganizer::Redo()
{



}
